<template>
  <doc-alert title="【营销】拼团活动" url="https://doc.iocoder.cn/mall/promotion-combination/" />
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form ref="queryFormRef" :model="queryParams" class="-mb-15px">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="开团团长" prop="headMember">
            <el-select
              v-model="queryParams.headMember"
              @change="handleQuery"
              filterable
              clearable
              placeholder="请输入开团团长ID/昵称/手机号"
            >
              <el-option
                v-for="item in options"
                :key="item.userId"
                :label="item.nickname"
                :value="item.userId"
              >
                <span>{{ item.nickname }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="参团会员" prop="member">
            <el-select
              v-model="queryParams.member"
              @change="handleQuery"
              filterable
              clearable
              placeholder="请输入参团会员ID/昵称/手机号"
            >
              <el-option
                v-for="item in options1"
                :key="item.userId"
                :label="item.nickname"
                :value="item.userId"
              >
                <span>{{ item.nickname }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="活动名称" prop="spuName">
            <el-input
              v-model="queryParams.spuName"
              clearable
              placeholder="请输入活动ID/活动名称"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              :shortcuts="defaultShortcuts"
              :disabled-date="disabledDate"
              end-placeholder="结束日期"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="拼团状态" prop="status">
            <el-select v-model="queryParams.status" clearable placeholder="全部">
              <el-option
                v-for="(dict, index) in getIntDictOptions(
                  DICT_TYPE.PROMOTION_COMBINATION_RECORD_STATUS
                )"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="排序方式" prop="sortType">
            <div class="flex w-full!">
              <div class="flex-1">
                <el-select v-model="queryParams.sortType" class="!w-125px" clearable>
                  <el-option :label="'按下单时间'" :value="0" />
                  <el-option :label="'按开团团长'" :value="1" />
                </el-select>
              </div>
              <div class="flex ml-10px">
                <el-radio-group v-model="queryParams.sortStatus" @change="handleQuery">
                  <el-radio-button label="正序" value="up">
                    <div class="flex"><Icon icon="ep:top" :size="14" /> </div>
                  </el-radio-button>
                  <el-radio-button label="倒序" value="down">
                    <div class="flex"><Icon icon="ep:bottom" :size="14" /> </div>
                  </el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon class="mr-5px" icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>
  <!-- 统计信息展示 -->
  <el-row :gutter="12">
    <el-col :span="8">
      <SummaryCard
        title="参与人数(个)"
        class="mb-10px"
        icon="fa:user-times"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        :decimals="0"
        :value="recordSummary.userCount"
      />
    </el-col>
    <el-col :span="8">
      <SummaryCard
        title="成团数量(个)"
        class="mb-10px"
        icon="fa:user-plus"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        :decimals="0"
        :value="recordSummary.successCount"
      />
    </el-col>
    <el-col :span="8">
      <SummaryCard
        title="虚拟成团(个)"
        class="mb-10px"
        icon="fa:user-plus"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        :decimals="0"
        :value="recordSummary.virtualGroupCount"
      />
    </el-col>
  </el-row>

  <!-- 分页列表数据展示 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="pageList">
      <el-table-column align="center" label="ID" prop="id" min-width="100" />
      <el-table-column label="参团会员" align="left" prop="avatar" min-width="150">
        <template #default="scope">
          <div class="flex">
            <div>
              <el-image
                :preview-teleported="true"
                :src="scope.row.avatar"
                class="w-[48px]! h-[48px]! m-r-10px rounded-4px align-middle"
              />
            </div>

            <el-text>{{ scope.row.nickname }}</el-text>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机" prop="mobile" min-width="130" />

      <el-table-column align="left" label="开团团长" prop="headId" min-width="150">
        <template #default="{ row }: { row: CombinationRecordApi.CombinationRecordVO }">
          <div class="flex">
            <div>
              <el-image
                :preview-teleported="true"
                :src="
                  row.headId ? pageList.find((item) => item.id === row.headId)?.avatar : row.avatar
                "
                class="w-[48px]! h-[48px]! m-r-10px rounded-4px align-middle"
              />
            </div>

            <el-text>{{
              row.headId ? pageList.find((item) => item.id === row.headId)?.nickname : row.nickname
            }}</el-text>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机" prop="mobile" min-width="130">
        <template #default="{ row }: { row: CombinationRecordApi.CombinationRecordVO }">
          {{ row.headId ? pageList.find((item) => item.id === row.headId)?.mobile : row.mobile }}
        </template>
      </el-table-column>
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="开团时间"
        prop="startTime"
        width="180"
      />
      <el-table-column label="拼团商品" prop="type" show-overflow-tooltip min-width="250">
        <template #default="{ row }">
          <el-image
            :src="row.picUrl"
            class="mr-5px !h-[48px] !w-[48px] border-rd-4px align-middle"
            @click="imagePreview(row.picUrl)"
          />
          <span class="align-middle">{{ row.spuName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="几人团" prop="userSize" min-width="100" />
      <el-table-column align="center" label="参与人数" prop="userCount" min-width="100" />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="参团时间"
        prop="startTime"
        width="180"
      />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="结束时间"
        prop="endTime"
        width="180"
      />
      <el-table-column align="center" label="拼团状态" prop="status" min-width="150">
        <template #default="scope">
          <dict-tag
            :type="DICT_TYPE.PROMOTION_COMBINATION_RECORD_STATUS"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" min-width="100" label="操作">
        <template #default="scope">
          <el-button
            v-hasPermi="['promotion:combination-record:query']"
            link
            type="primary"
            @click="openRecordListDialog(scope.row)"
          >
            查看拼团
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗 -->
  <CombinationRecordListDialog ref="combinationRecordListRef" />
</template>
<script lang="ts" setup>
import CombinationRecordListDialog from './CombinationRecordListDialog.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter, defaultShortcuts } from '@/utils/formatTime'
import { createImageViewer } from '@/components/ImageViewer'
import * as CombinationRecordApi from '@/api/mall/promotion/combination/combinationRecord'
/**时间范围限制 */
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
defineOptions({ name: 'PromotionCombinationRecord' })

const queryParams = ref({
  status: undefined, // 拼团状态
  createTime: undefined, // 创建时间
  pageSize: 10,
  pageNo: 1,
  type: 0,
  headMember: '',
  member: '',
  spuName: '',
  sortType: 0, //排序类型
  sortStatus: 'up' //排序状态
})
const queryFormRef = ref() // 搜索的表单
const combinationRecordListRef = ref() // 查询表单 Ref
const loading = ref(true) // 列表的加载中
const total = ref(0) // 总记录数
const pageList = ref<CombinationRecordApi.CombinationRecordVO[]>([]) // 分页数据

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CombinationRecordApi.getCombinationRecordPage(queryParams.value)
    pageList.value = data.list as CombinationRecordApi.CombinationRecordVO[]
    total.value = data.total
  } finally {
    loading.value = false
  }
}
// 拼团统计数据
const recordSummary = ref({
  successCount: 0,
  userCount: 0,
  virtualGroupCount: 0
})
/** 获得拼团记录统计信息 */
const getSummary = async () => {
  recordSummary.value = await CombinationRecordApi.getCombinationRecordSummary({ type: 0 })
}
/** 获得拼团用户信息 */
const options = ref<any[]>([])
const options1 = ref<any[]>([])
const getListMember = async () => {
  options.value = await CombinationRecordApi.getCombinationListMember({ headId: 0 })
  options1.value = await CombinationRecordApi.getCombinationListMember({ headId: 1 })
}

/** 查看拼团详情 */
const openRecordListDialog = (row: CombinationRecordApi.CombinationRecordVO) => {
  combinationRecordListRef.value?.open(row.headId || row.id) // 多表达式的原因，团长的 headId 为空，就是自身的情况
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/** 初始化 **/
onMounted(async () => {
  await getSummary()
  await getList()
  await getListMember()
})
</script>
